/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pneuservis.frontend.web;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.util.JdbcUtils;

/**
 *
 * @author jajaja
 */
public class SecurityJdbcRealm extends JdbcRealm{

    public SecurityJdbcRealm() {
        super();
        InitialContext ctx;
        DataSource dataSource;
        
        try {
            ctx = new InitialContext();
            dataSource = (DataSource) ctx.lookup("jdbc/__default");
//            dataSource = (DataSource) ctx.lookup("java:app/jdbc/pa165");
            this.setDataSource(dataSource);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
    
    @Override
        protected Set getRoleNamesForUser(Connection conn, String username) throws SQLException { 
        PreparedStatement ps = null;  
        ResultSet rs = null;  
        Set roleNames = new LinkedHashSet();  
  
        try {  
            ps = conn.prepareStatement(userRolesQuery);  
            ps.setString(1, username);  
          
  
            // Execute query  
            rs = ps.executeQuery();  
  
            // Loop over results and add each returned role to a set  
            while (rs.next()) {  
  
                String roleName = rs.getString(1).toLowerCase();  
  
                // Add the role to the list of names if it isn't null  
                if (roleName != null) {  
                    roleNames.add(roleName);  
                } 
                  
            }  
        } finally {  
            JdbcUtils.closeResultSet(rs);  
            JdbcUtils.closeStatement(ps);  
        }  
  
        return roleNames;  
    }       
    
}
